/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-14 18:55:39
 */
/**
 * 该文件是用来操作登录、注册、获取用户信息、token 等操作，
 * 📢🔈📣几乎全部需要重写，不分析了 ❗❗❗
 */

import { defineStore } from 'pinia'

// 导入操作 Token 的方法
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { UserInfoState } from './interface'
import { allAsyncRoutes, staticRoutes } from '@/router/routes'
import { reqLogin, reqUserInfo, type IReqUserInfo, reqLogout } from '@/api/user'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {} as IReqUserInfo,
    menuRoutes: [...staticRoutes, ...allAsyncRoutes]
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const res = await reqLogin(username, password)
      if (res.code === 20000) {
        this.token = res.data.token
        setToken(res.data.token)
        Promise.resolve(true)
      } else {
        Promise.reject(false)
      }
    },

    // 获取用户信息
    async getInfo() {
      const res = await reqUserInfo()
      console.log(res)

      if (res.code === 20000) {
        this.userInfo = res.data
      }
    },

    // 退出功能
    async reset() {
      const res = await reqLogout()
      if (res.code === 20000) {
        this.token = ''
        this.userInfo = {} as IReqUserInfo
        removeToken()
      }
    }
  }
})
